package com.siysoft.util;

import java.io.Serializable;
import java.util.StringTokenizer;


/**
 * @author dell
 *
 */
public class StringUtil {
   public static String escapeEscape(String str) {
      StringBuffer buf = new StringBuffer();

      for(int i = 0; i < str.length(); i++) {
         if(str.charAt(i) == '\\') {
            buf.append("\\");
         }

         buf.append(str.charAt(i));
      }

      return buf.toString();
   }
   
	public static long indexOf(String sourceString, String lookFor) {
        byte[] sourceStringList;
        byte[] lookForList;
        long index = -1;
        int i;
        int j;
        try {
                // Load the source string
                sourceStringList=sourceString.getBytes();

                // Load the string for search
                lookForList=lookFor.getBytes();

                if (lookFor.length()==0) {
                        return 0;
                }
                // Scan source string to search
                for (i = 0; i < sourceStringList.length; i++) {
                        if (lookForList.length > 0
                                        && sourceStringList[i]==lookForList[0]) {
                                // Start to do further analyze
                                for (j = 0; j < lookForList.length; j++) {
                                        if (sourceStringList[i + j]!=lookForList[j]) {
                                                // Give up look up
                                                index = -1;
                                                break;
                                        }
                                        index = i;
                                }
                                if (index != -1) {
                                        // Find the string
                                        break;
                                }
                        }
                }
                return index;
        } finally {
                sourceStringList = null;
                lookForList = null;
        }
}
    /**
     * 将ISO8859_1编码的字符串转码为GBK编码
     * @param s 源串
     * @return 结果�?
     */
    public static String UNI2GBK(String s) {
        String temp = "";
        try {
            if (s!=null) {
                temp = s;
                temp = new String(s.getBytes(),"GBK");
            }
        } catch (Exception e) {
        } finally {
            return temp;
        }
    }

   /**
     * 将GBK编码的字符串转码为ISO8859_1编码
     * @param s 源串
     * @return 结果�?
     */
    public static String GBK2UNI(String s) {
        String temp = "";
        try {
            if (s!=null) {
                temp = s;
                temp = new String(s.getBytes("GBK"), "ISO8859_1");
            }
        } catch (Exception e) {

        } finally {
            return temp;
        }
    }

    public static String GBK2UTF_8(String s) {
        String temp = "";
        try {
            if (s!=null) {
                temp = s;
                temp = new String(s.getBytes("GBK"), "UTF_8");
            }
        } catch (Exception e) {

        } finally {
            return temp;
        }
    }

    /**
     *
     * <pre>
     *   字符串替换函�?
     * </pre>
     * @param from 要替换的字符
     * @param to 要替换成的目标字�?
     * @param source 要替换的字符�?
     * @return 替换后的字符�?
     * @add-time: 2007-01-27
     * @add-athname:  guke
     */
    public static String replace(String strSource, String strFrom, String strTo) {
        if (strSource == null) {
          return null;
        }
        int i = 0;
        if ((i = strSource.indexOf(strFrom, i)) >= 0) {
          char[] cSrc = strSource.toCharArray();
          char[] cTo = strTo.toCharArray();
          int len = strFrom.length();
          StringBuffer buf = new StringBuffer(cSrc.length);
          buf.append(cSrc, 0, i).append(cTo);
          i += len;
          int j = i;
          while ((i = strSource.indexOf(strFrom, i)) > 0) {
            buf.append(cSrc, j, i - j).append(cTo);
            i += len;
            j = i;
          }
          buf.append(cSrc, j, cSrc.length - j);
          return buf.toString();
        }
        return strSource;
      }

    /**
     * <pre>
     *   取得字符串的编码
     * </pre>
     *
     * @param stream 要变换的字符�?
     * @return 字符串的编码(１６进制)
     * @add-time: 2007-02-01
     * @add-athname:  guke
     */
    public static String toStrCode(String stream) {
      if (stream == null || stream.length() == 0) {
        return stream;
      }

      byte[] bytes = null;
      try {
        bytes = stream.getBytes("gb2312");
      } catch (Exception e) {
        bytes = stream.getBytes();
      }

      StringBuffer buffer = new StringBuffer();
      if (bytes != null) {
        for (int lopcnt = 0; lopcnt < bytes.length; lopcnt++) {
          buffer.append(Integer.toHexString(bytes[lopcnt] & 0x0000FF));
        }
      }

      return buffer.toString().toUpperCase();
    }

    /**
     * <pre>
     *  从字符串的编码转换成字符�?
     * </pre>
     *
     * @param stream 字符串的编码(１６进制)
     * @return 变换成的字符�?
     * @add-time: 2007-02-01
     * @add-athname:  guke
     */
    public static int hexToDec(String stream) {
      if (stream == null || stream.length() == 0) {
        return Integer.MIN_VALUE;
      }

      try {
        return Integer.parseInt(stream, 16);
      } catch (Exception e) {
        return Integer.MIN_VALUE;
      }
    }

    /**
     * 判断字符串是否为�?
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
		if (str == null || str.equals("")) {
			return true;
		} else {
			return false;
		}
	}
	public static boolean isBlank(Serializable str) {
		if (str == null) {
			return true;
		} else {
			if (((String) str).equals("")) {
				return true;
			}
			return false;
		}
	}

	public static boolean isBlank(Object obj) {
		if (obj == null) {
			return true;
		} else {
			if (((String) obj).equals("")) {
				return true;
			}
			return false;
		}
	}

	/**
	 * �?查一个字符串数组中是否含有指定的字符
	 * @param str
	 * @param source
	 * @return 0:包含;1:�?查出现异�?;-1:不包�?
	 */
	public static int testStringInString(String str,String[] source){
		try{
			for(int i=0;i<source.length;i++){
				if(str.equals(source[i])) return 0;
			}
		}catch(Exception e){
			e.printStackTrace();
			return 1;
		}
		return -1;
	}
	/**
	 * �?查一个字符串中是否含有指定的字符
	 * @param str:要查找的字符
	 * @param source:
	 * @param splits:
	 * @return
	 */
	public static int testStringInString(String str,String source,String splits){
		String[] tempS = source.split(splits);
		try{
			for(int i=0;i<tempS.length;i++){
				if(str.equals(tempS[i])) return 0;
			}
		}catch(Exception e){
			e.printStackTrace();
			return 1;
		}
		return -1;
	}

	public static String setStrings(String str, int len) {
		int strlen = 0;
		String s = "";

		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) > 128)
				strlen += 2;
			else
				strlen++;
			s += str.charAt(i);
			if (strlen >= len)
				return s + "...";
		}
		return s;
	}

	public static String setStrings2(String str, int len) {
		int strlen = 0;
		String s = "";

		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) > 128)
				strlen += 2;
			else
				strlen++;
			s += str.charAt(i);
			if (strlen >= len)
				return s;
		}
		return s;
	}

	public static String setStrings3(String str, int len) {
		int strlen = 0;
		String s = "";

		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) > 128)
				strlen += 2;
			else
				strlen++;
			s += str.charAt(i);
			if (strlen > len)
				return s + "�?";
		}
		return s;
	}

	public static String null2String(String str)
	{
		if(str==null)
			str = "";
		return str;
	}

	public static int string2Int(String str)
	{
		if(str==null || str.equals(""))
			return 0;
		try{
			return Integer.parseInt(str);
		}
		catch(Exception e)
		{
			return 0;
		}

	}

	public static Long string2Long(String str)
	{
		if(str==null || str.equals(""))
			return new Long(0);
		try{
			return Long.parseLong(str);
		}
		catch(Exception e)
		{
			return new Long(0);
		}

	}

	public static Double string2Double(String str)
	{
		if(str==null || str.equals(""))
			return new Double(0);
		try{
			return new Double(Double.parseDouble(str));
		}
		catch(Exception e)
		{
			return new Double(0);
		}

	}

	public static boolean isEmpty(String param) {
        return (param == null || param.trim().length() == 0) ? true : false;
	}

	 public static String upperCaseFirstChar(String param) {
         if (isEmpty(param))
                 return null;
         StringBuffer sb = new StringBuffer(param.length());
         for (int i = 1; i < param.length(); i++) {
                 sb.append(param.charAt(i));
         }
         return (param.substring(0, 1).toUpperCase()) + sb.toString();
	 }

	 public static Double string2Sum(String[] str) {
		Double sum = 0.00;
		String Str = "";
		if (str != null) {
			for (int i = 0; i < str.length; i++)
					Str += str[i] + ",";
		} else
			Str = "''";
		if (str.length==1){
			StringTokenizer token = new StringTokenizer(Str, ",");
			while (token.hasMoreTokens())
				 sum = Double.parseDouble(token.nextToken());
			}
		else{
			StringTokenizer token = new StringTokenizer(Str, ",");
			while (token.hasMoreTokens())
				sum += Double.valueOf(token.nextToken());
		}
		return sum;
	}

	public static String citytoken(String type,String str)
	{
		if(isBlank(str)){
			return "";
		}
		else
		{
			StringTokenizer token = new StringTokenizer(str,"|");
			String province = "";
			String city = "";
			int i=0;
			while(token.hasMoreTokens())
			{

				if(i==0)
					province = token.nextToken();
				else
					city = token.nextToken();
				i++;
			}
			if(type.equals("province"))
				return province;
			else if(type.equals("city"))
				return city;
			else
				return "";
		}

	}
	/**
	 * 数组分割
	 * Author wangyf 
	 * @param strs
	 * @return
	 */
	public static String arrayToString(String [] strs){
		if(strs==null){
			return "";
		}else {
			String result = ""; 
			String seprater = "|"; 
			for (int i = 0; i < strs.length; i++) { 
			   result += strs[i]+seprater; 
			} 
			return result;
		}
	}
	public static String takeOutTrim(String str) {
		
		if (str==null || str.equals("")) {
			return"";
		}
		String str2 = ""; //去空格后的字符串
        String[] str1 = str.split(" "); //把原字符串按空格分割
        for(int i = 0;i<str1.length;i++)
        {
            if(str1[i] != "") 
            {
                str2 += str1[i]; //
            }
        }
        return str2;
	}
	
	public static String htmEncode(String s)
	{
	        StringBuffer stringbuffer = new StringBuffer();
	        int j = s.length();
	        for(int i = 0; i < j; i++)
	        {
	            char c = s.charAt(i);
	            switch(c)
	            {
	            case 60: stringbuffer.append("&lt;"); break;
	            case 62: stringbuffer.append("&gt;"); break;
	            case 38: stringbuffer.append("&amp;"); break;
	            case 34: stringbuffer.append("&quot;"); break;
	            case 169: stringbuffer.append("&copy;"); break;
	            case 174: stringbuffer.append("&reg;"); break;
	            case 165: stringbuffer.append("&yen;"); break;
	            case 8364: stringbuffer.append("&euro;"); break;
	            case 8482: stringbuffer.append("&#153;"); break;
	            case 13:
	              if(i < j - 1 && s.charAt(i + 1) == 10)
	              {stringbuffer.append("<br>");
	               i++;
	              }
	              break;
	            case 32:
	              if(i < j - 1 && s.charAt(i + 1) == ' ')
	                {
	                  stringbuffer.append(" &nbsp;");
	                  i++;
	                  break;
	                }
	            default:
	                stringbuffer.append(c);
	                break;
	            }
	        }
	      return new String(stringbuffer.toString());
	} 
	
	
	
	public static String string2Json(String s) {     
	    StringBuffer sb = new StringBuffer ();     
	    for (int i=0; i<s.length(); i++) {     
	   
	        char c = s.charAt(i);     
	        switch (c) {    
		        case '\\':     
		            sb.append("\\\\");     
		            break;     
		        case '/':     
		            sb.append("\\/");     
		            break;     
		        case '\b':     
		            sb.append("\\b");     
		            break;     
		        case '\f':     
		            sb.append("\\f");     
		            break;     
		        case '\n':     
		            sb.append("\\n");     
		            break;     
		        case '\r':     
		            sb.append("\\r");     
		            break;     
		        case '\t':     
		            sb.append("\\t");     
		            break;     
		        default:     
		            sb.append(c);     
	        }
	    }
	    return sb.toString();   
	 }  
	
	public static String htmlEncode(int i){
		
		if (i=='&') {
			return "&amp;";
		}else if (i=='<') {
			return "&lt;";
		}else if (i=='>') {
			return "&gt;";
		}else if (i=='"') {
			return "&quot;";
		}
		else return ""+(char)i;
	}
	
	public static String htmlEncode(String st){
		StringBuffer buffer = new StringBuffer();
		
		for (int i = 0; i < st.length(); i++) {
			
			buffer.append(htmlEncode(st.charAt(i)));
		}
		
		return buffer.toString();
	}
	
	public static void main(String [] args)
	{
		String [] tids = {"aaa","bbb"};
		String result = ""; 
		String seprater = ","; 
		for (int i = 0; i < tids.length; i++) { 
		   result += tids[i]+seprater; 
		} 
		System.out.println("result:" + result);

		System.out.println(citytoken("city","北京|海淀"));
		System.out.println(string2Double("fff"));
		String str = "        ";
		System.out.println(str.length());
		System.out.println(str.trim().length());
		System.out.println(takeOutTrim("    sdsdsd"));
	}

}
